package me.leiusual.sharing.ui.shop

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_shop_withdraw_edit.*
import kotlinx.android.synthetic.main.view_holder_shop_bank.view.*
import me.leiusual.sharing.R
import me.leiusual.sharing.api.model.WithdrawCreate
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.MainViewModel
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.util.extension.toast
import timber.log.Timber
import javax.inject.Inject

/**
 * author: leiusual
 * create on: 2019-08-01
 * description:
 */
class ShopWithdrawEditFragment : DaggerFragment(), View.OnClickListener {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val mainViewModel: MainViewModel by activityViewModels { factory }

  private val viewModel: ShopWithdrawEditViewModel by viewModels { factory }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_shop_withdraw_edit, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }

    text_view_account.setOnClickListener(this)
    text_view_bank_account.setOnClickListener(this)
    include_view_holder_shop_bank.setOnClickListener(this)
    button_update.setOnClickListener(this)

    observeData()
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.text_view_account -> {
        viewModel.withdrawAccount()
      }
      R.id.text_view_bank_account, R.id.include_view_holder_shop_bank -> {

        // 选择提现账户
        val action = ShopWithdrawEditFragmentDirections.actionShopWithdrawEditFragmentToShopBankFragment(true)
        findNavController().navigate(action)
      }
      R.id.button_update -> {

        // 创建
        doWithdrawCreate()
      }
    }
  }

  private fun observeData() {
    viewModel.withdrawAccount.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("withdrawAccount = %s", it)
      when (it) {
        is Data.Loading -> {
          // ignore
        }
        is Data.Error -> {
          toast(it.error.message)
        }
        is Data.Success -> {

          // 显示可选账户
          dialogAccountType(it.data)
        }
      }
    })

    viewModel.withdrawAccountSelected.observe(viewLifecycleOwner, Observer {
      Timber.v("withdrawAccountSelected = %s", it)

      // 显示选中数据
      text_view_account.text = it.values.firstOrNull()
    })

    mainViewModel.bank.observe(viewLifecycleOwner, Observer {
      Timber.v("bank = %s", it)

      // 显示银行账户
      if (it == null) {
        text_view_bank_account.isVisible = true
        include_view_holder_shop_bank.isVisible = false
      } else {
        text_view_bank_account.isVisible = false
        include_view_holder_shop_bank.isVisible = true

        include_view_holder_shop_bank.text_view_card_owner_name.text = it.cardOwnerName
        include_view_holder_shop_bank.text_view_bank_card_id.text = it.bankCardId
        include_view_holder_shop_bank.text_view_default.isVisible = it.defaultAccount
        include_view_holder_shop_bank.text_view_bank_name.text = it.bankName
        include_view_holder_shop_bank.image_button_edit.setImageResource(R.drawable.ic_nav_arrow)
      }
    })

    viewModel.withdrawCreate.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("withdrawCreate = %s", it)
      when (it) {
        is Data.Loading -> {
          button_update.isEnabled = false
        }
        is Data.Error -> {
          button_update.isEnabled = true
          toast(it.error.message)
        }
        is Data.Success -> {
          button_update.isEnabled = true
          findNavController().popBackStack()
        }
      }
    })
  }

  private fun dialogAccountType(map: Map<String, String>) {
    val values = map.values.toTypedArray()
    AlertDialog.Builder(requireContext())
        .setItems(values) { _, witch ->
          viewModel.withdrawAccountSelected(map.filterValues { it == values[witch] })
        }
        .show()
  }

  private fun doWithdrawCreate() {
    val accountType = viewModel.withdrawAccountSelected.value
    if (accountType == null || accountType.isEmpty()) {
      toast("请选择账户类型")
      return
    }

    val amount = edit_text_amount.text.toString().toLongOrNull()
    if (amount == null) {
      toast("请输入提现金额")
      return
    }

    val bankAccount = mainViewModel.bank.value
    if (bankAccount == null) {
      toast("请选择提现账户")
      return
    }

    val request = WithdrawCreate.Request(accountType.keys.first(), amount, bankAccount.id)
    viewModel.withdrawCreate(request)
  }
}